package com.luckilyswl.httpdemo;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.ColorUtils;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.luckilyswl.httpdemo.adapter.LaughAdapter;
import com.luckilyswl.httpdemo.bean.LaughData;
import com.luckilyswl.httpdemo.util.WindowUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private RecyclerView mLaughRecycler;
    private LaughAdapter laughAdapter;
    private LaughData dataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowUtil.setStatusBarBgColor(this,getResources().getColor(R.color.colorWite));
        setContentView(R.layout.activity_main);

        initData();
        initHandler();
        initView();
    }

    private Handler handler;

    private void initHandler() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                laughAdapter.ChangeData(dataBean);  // 提示更新数据
                return false;
            }
        });
    }

    private void initData() {
        OkHttpClient  client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("http://v.juhe.cn/joke/content/list.php?key=1f3abc260f796cea6c464b8f71929702&page=2&pagesize=10&sort=asc&time=1418745237")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure", "onFailure: "+" 请求失败" );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String dataJsonStr = response.body().string();

                dataBean = new Gson().fromJson(dataJsonStr,LaughData.class);
                handler.sendEmptyMessage(1001);
            }
        });
    }


    private void initView() {
        mLaughRecycler = findViewById(R.id.list_recycler);
        mLaughRecycler.setLayoutManager(new GridLayoutManager(this,1));
        laughAdapter = new LaughAdapter(this,dataBean);
        mLaughRecycler.setAdapter(laughAdapter);
    }
}
